package com.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Util {

	private Util() {
	}

	private final static Logger LOG = LoggerFactory.getLogger(Util.class);
	private final static String DATEFORMAT = "yyyy-MM-dd";

	public static String date2Str(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
		return sdf.format(date);
	}

	/**
	 * SHA加密 （单向加密）
	 * 
	 * @param data
	 * @return
	 * @throws Exception
	 */
	private static final String KEY_SHA = "SHA-1";

	public static String encryptSHA(String src) {

		MessageDigest sha;
		try {
			byte[] data = src.getBytes("UTF-8");
			sha = MessageDigest.getInstance(KEY_SHA);
			sha.update(data);
			String encodeStr = byte2Hex(sha.digest());
			return encodeStr;
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
			LOG.error(e.getMessage());
			return src;
		}

	}

	/**
	 * jdk base64 两层加密 sun.misc
	 * 
	 * @param src
	 * @return
	 */
	public static String bas64Encode(String src) {
		Encoder base64Encoder = Base64.getEncoder();
		return base64Encoder.encode(base64Encoder.encode(src.getBytes())).toString();
	}

	/**
	 * jdk base64解密 sun.misc
	 * 
	 * @param encodeData
	 * @return
	 */
	public static String bas64Decode(String encodeData) {
		Decoder base64Decoder = Base64.getDecoder();
		return new String(base64Decoder.decode((new String(base64Decoder.decode(encodeData)))));
	}

	private static String byte2Hex(byte[] bytes) {
		StringBuffer stringBuffer = new StringBuffer();
		String temp = null;
		for (int i = 0; i < bytes.length; i++) {
			temp = Integer.toHexString(bytes[i] & 0xFF);
			if (temp.length() == 1) {
				// 1得到一位的进行补0操作
				stringBuffer.append("0");
			}
			stringBuffer.append(temp);
		}
		return stringBuffer.toString();
	}
}
